package com.qiniu;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.util.Auth;

public class MainActivity extends Activity implements UpCompletionHandler, UpProgressHandler, UpCancellationSignal{

	private static final String AK = "MRwLNFYyKA5dICAFAhin_Sn-6MkLB4DR3EywPMjK";

	private static final String SK = "q6eCQ66BeH7BiKP1ye2tPka4eSDOgARc7t9koCmu";
	
	private volatile boolean isCancelledUpload;

	private static final Auth auth = Auth.create(AK, SK);
	
	private TextView tv;
	
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			tv.setText(msg.obj.toString());
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv = (TextView) findViewById(R.id.tv);
	}

	public void upload(View view) {
		isCancelledUpload = false;
		pickPhoto();
	}
	
	public void cancelUpload(View view) {
		isCancelledUpload = true;
	}

	public static String getUpToken() {
		return auth.uploadToken("warmchat");
	}

	private void showToast(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 从相册中选择图片
	 * 
	 * @param requestCode
	 *            选择的图片Uri，在onActivityResult中使用data.getData();获取
	 */
	private void pickPhoto() {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(intent, 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK && data != null) {
			String path = getPathFromUri(this, data.getData());
			QiniuUtils.upload(path, System.currentTimeMillis() + ".jpg", getUpToken(), this, this, this);
		}
	}
	
	/**
	 * 从拍照、相册中选择图片中选择的Uri中，获取图片的实际路径
	 * 
	 * @param context
	 * @param uri
	 * @return
	 */
	private String getPathFromUri(Context context, Uri uri) {

		String picPath = null;
		String[] pojo = { MediaStore.Images.Media.DATA };

		Cursor cursor = context.getContentResolver().query(uri, pojo, null,
				null, null);
		if (cursor != null && !cursor.isClosed()) {
			int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
			cursor.moveToFirst();
			picPath = cursor.getString(columnIndex);
			try {
				if (Build.VERSION.SDK_INT < 14) {
					cursor.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return picPath;
	}

	@Override
	public void complete(String arg0, ResponseInfo response, JSONObject json) {
		Log.e("Log", new Gson().toJson(response));
		Log.e("Log", new Gson().toJson(json));
		try {
			int statusCode = new JSONObject(new Gson()
					.toJson(response)).getInt("statusCode");
			if (statusCode == 200) {
				showToast("上传成功");
				return;
			}
			else if(statusCode == -2){
				showToast("用户取消");
				return;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		showToast("失败");
	}

	@Override
	public void progress(String key, double percent) {
		Message msg = new Message();
		msg.obj = key + ":" + (int)(percent * 100) + "%";
		handler.sendMessage(msg);
	}

	@Override
	public boolean isCancelled() {
		return isCancelledUpload;
	}
}
